import time
import json

from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.utils import timezone

from .models import Question, Answer
from .chat import ErnieChat, SparkChat, GPT4Chat


def index(request):
    return render(request, "api/index.html")


@csrf_exempt
def test(request):
    response = {
        "text": "recived a request",
        "time": time.strftime(
                    "%Y/%m/%d %H:%M:%S",
                    time.localtime()
                ),
    }
    return JsonResponse(response)


@csrf_exempt
def create_question(request):
    print(request.body)
    text = json.loads(request.body.decode())["text"]
    try:
        name = json.loads(request.body.decode())["name"]
    except KeyError:
        name = "<unknow>"
    q = Question(name=name, text=text, publish_date=timezone.now())
    q.save()

    return JsonResponse({"id": q.id})


def get_question(request):
    id_ = request.POST["id"]
    q = Question.objects.get(id=id_)
    return q.text

@csrf_exempt
def chat_with_ernie(request):
    bot = ErnieChat
    return _chat(request, bot)


@csrf_exempt
def chat_with_spark(request):
    bot = SparkChat
    return _chat(request, bot)


@csrf_exempt
def chat_with_GPT4Chat(request):
    bot = GPT4Chat
    return _chat(request, bot)


@csrf_exempt
def _chat(request, bot):
    try:
        q_id = json.loads(request.body.decode())["q_id"]
    except KeyError as e:
        return HttpResponse(
            f"[Error] The key {str(e)} is not found in request")
    q = Question.objects.get(id=q_id)
    bot_instance = bot()
    a_text = bot_instance.chat(q.text)
    a = Answer(
        text=a_text,
        publish_date=timezone.now(),
        question=q,
        model_name=bot_instance.name
    )
    a.save()
    return JsonResponse(
        {
            "model": bot_instance.name,
            "text": a_text,
            "id": a.id,
        }
    )


@csrf_exempt
def vote_like(request):
    try:
        a_id = json.loads(request.body.decode())["id"]
        print(a_id)
    except KeyError as e:
        return HttpResponse(
            f"[Error] The key {str(e)} is not found in request")
    try:
        a = Answer.objects.get(pk=a_id)
    except Answer.DoesNotExist:
        return HttpResponse(
            f"[Error] The Answer(pk={a_id}) not found")
    a.likes = a.likes + 1
    a.save()
    return JsonResponse()


@csrf_exempt
def vote_dislike(request):
    try:
        a_id = json.loads(request.body.decode())["id"]
        print(a_id)
    except KeyError as e:
        return HttpResponse(
            f"[Error] The key {str(e)} is not found in request")
    try:
        a = Answer.objects.get(pk=a_id)
    except Answer.DoesNotExist:
        return HttpResponse(
            f"[Error] The Answer(pk={a_id}) not found")
    a.dislikes = a.dislikes + 1
    a.save()
    return JsonResponse()
